package com.situ.vivamarket.api.sys;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.situ.vivamarket.model.Admin;
import com.situ.vivamarket.model.search.AdminSearchBean;
import com.situ.vivamarket.service.AdminService;
import com.situ.vivamarket.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/sys/api/v1/admin")
public class AdminApi {
    private AdminService adminService;
//    依赖注入
    @Autowired
    public void setAdminService(AdminService adminService) {
        this.adminService = adminService;
    }



    @GetMapping
    public ResponseEntity<JsonResult> list(AdminSearchBean asb,
                                           @RequestParam (defaultValue = "1") Integer page,
                                           @RequestParam (defaultValue = "10")Integer limit) {

        Page<?> p= new Page<>(page, limit);//分页对象

        List<Admin> admins = adminService.getAllAdmins(asb,p);
        PageInfo<Admin> pi = new PageInfo<>(admins);
        JsonResult result=JsonResult.successData(admins);
        result.setCount((int)pi.getTotal());
        return ResponseEntity.ok(result);
    }

    @DeleteMapping
    public ResponseEntity<JsonResult> delete(Integer[] ids) {
        if(ids.length == 0){
            return ResponseEntity.noContent().build();
        }else{
            int count=adminService.deleteByIds(ids);
            if(count>0){
                return ResponseEntity.ok(JsonResult.successData(count));
            }else{
                return ResponseEntity.ok(JsonResult.fail("删除管理员失败"));
            }
        }
    }
    @PostMapping
    public ResponseEntity<JsonResult> add( @Validated(AdmAddGroup.class) Admin admin) {
//       使用validated进行参数校验，校验失败，会抛出异常
        boolean success=adminService.add(admin);

        return success ? ResponseEntity.ok(JsonResult.successData(admin))
                : ResponseEntity.internalServerError().body(JsonResult.fail("新增管理员异常"));
    }
    @PutMapping
    public ResponseEntity<JsonResult> update(@Validated(AdmEditGroup.class) Admin admin) {
        //       使用validated进行参数校验，校验失败，会抛出异常
        boolean success=adminService.update(admin);
        return success ? ResponseEntity.ok(JsonResult.successData(admin))
                : ResponseEntity.internalServerError().body(JsonResult.fail("修改管理员失败"));
    }

    @PatchMapping
    public ResponseEntity<JsonResult> patch(@RequestBody Admin admin) {
        admin.setUpdatedTime(LocalDateTime.now());
        boolean success=adminService.patch(admin);
        return  success ? ResponseEntity.ok(JsonResult.success("修改管理员成功"))
                : ResponseEntity.internalServerError().body(JsonResult.fail("修改管理员失败"));
    }
}
